package com.wuliang.generate.common.core.configs;

import com.wuliang.generate.common.core.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 全局AOP配置
 *
 * @author 邬魉
 */
@Slf4j
@Aspect
@Component
public class AopConfig {

    @Pointcut("execution(public com.wuliang.generate.common.core.response.Result com.wuliang.generate.response.*.controller.*.*(..))")
    public void controllerPointcut() {
    }

    @Pointcut("execution(public * com.wuliang.generate.common.core.utils.*.*(..))")
    public void utilsPointcut() {
    }

    @Before("controllerPointcut()")
    public void beforeControllerPointcut(JoinPoint joinPoint) {
        // 方法名
        String mappingMethodName = joinPoint.getSignature().getName();
        // Controller
        String controllerName = joinPoint.getSignature().getDeclaringType().getSimpleName();
        Object[] argsValues = joinPoint.getArgs();
        String[] argsNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        Map<String, Object> jsonObject = new LinkedHashMap<>();
        for (int i = 0; i < argsValues.length; i++) {
            jsonObject.put(argsNames[i], argsValues[i]);
        }
        log.info("{}.{} 收到参数 [{}]", controllerName, mappingMethodName, JsonUtils.toJson(jsonObject));
    }

    @After("controllerPointcut()")
    public void afterControllerPointCut(JoinPoint joinPoint) {
        System.out.println(Arrays.toString(joinPoint.getArgs()));
    }

    @Around("controllerPointcut()")
    public Object aroundControllerPointCut(ProceedingJoinPoint pjp) throws Throwable {
        return pjp.proceed();
    }

    @Before("utilsPointcut()")
    public void beforeUtilsPointcut(JoinPoint joinPoint) {
        String utilsName = joinPoint.getTarget().getClass().getSimpleName();
        log.info("The util of {} will invoke", utilsName.substring(0, utilsName.length() - 5));
    }
}
